// pages/level/level.js
import api from "../../config/api";
import { shareOptions } from "../../utils/access";
import request from "../../utils/request";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 用户id
    id: null,
    // 用户信息
    info: {},
    // 等级列表
    list: [],
    // 当前等级id
    levelId: null,
    // 当前显示等级
    current: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id: options?.id,
      levelId: options?.levelId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLevel()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getLevel()
		wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 获取用户信息
	async getInfo(list) {
		const userId = this.data.id
		if (userId) {
      const res = await request.get(api.homeDetail, { userId  })
      const days = res?.data?.days || 0
      let currentIndex = list?.findIndex?.(l => (days < l.number && days !== l.number))
      if(days==list[list.length-1].number){
        currentIndex = 8
      }
      let currentSelectIndex = list.findIndex(l => l.id === +this.data.levelId)
      //目前current最大为6
      if(currentSelectIndex>6){
        currentSelectIndex = 6
      }
      console.log('currentSelectIndex',currentSelectIndex);
			this.setData({
        current: currentSelectIndex < 0 ? null : currentSelectIndex,
				info: {
          ...res?.data,
          current: {
            ...list[currentIndex],
            star: currentIndex % 3,
            index: currentIndex
          }
				}
			})
		}
	},
  // 获取环保等级
	async getLevel() {
    const res = await request.get(api.levelList)
    const list = [
      ...res?.data
    ]

    this.setData({
      list
    })
    this.getInfo(list)
	},
  // 用户点击右上角分享
  onShareAppMessage(e) {
    return shareOptions('default', e)
  }
})